import {
  request
} from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime'
import PubSub from 'pubsub-js'
import moment from 'moment'


const appInstance = getApp()
Page({

  data: {
    isPlay: false,
    song: {},
    currentId: "",
    musicLink: "",
    currentTime: "00:00",
    durationTime: "00:00",
    currentWidth: 0,
    isLove: false,
    isLoop: false
  },

  onLoad: function (options) {
    let currentId = options.id

    this.setData({
      currentId
    })
    this.getMusicDetail(currentId)

    if (appInstance.globalData.isMusicPlay && appInstance.globalData.musicId === currentId) {
      this.setData({
        isPlay: true
      })
    } else {
      this.setData({
        currentWidth: 0,
        currentTime: "00:00",
      })
    }

    //创建控制音乐播放的实例
    this.backgroundAudio = wx.getBackgroundAudioManager();

    this.backgroundAudio.onPlay(() => {
      this.changePlayState(true)

      //修改全局音乐播放状态
      // appInstance.globalData.isMusicPlay = true
      appInstance.globalData.musicId = currentId
    })
    this.backgroundAudio.onPause(() => {
      this.changePlayState(false)
    })
    this.backgroundAudio.onStop(() => {
      this.changePlayState(false)
    })


    this.backgroundAudio.onEnded(() => {

      let {
        isLoop
      } = this.data

      if (isLoop) {
        this.backgroundAudio.stop()
        //发布消息
        PubSub.publish('switchType', "loop")
        //订阅消息
        PubSub.subscribe("musicId", (msg, musicId) => {

          this.getMusicDetail(musicId)

          this.musicControl(true, musicId)

          //取消订阅
          PubSub.unsubscribe("musicId")
        })
      } else {

        this.backgroundAudio.stop()
        //发布消息
        PubSub.publish('switchType', "next")
        //订阅消息
        PubSub.subscribe("musicId", (msg, musicId) => {

          this.getMusicDetail(musicId)

          this.musicControl(true, musicId)

          //取消订阅
          PubSub.unsubscribe("musicId")
        })
      }
      this.setData({
        currentWidth: 0,
        currentTime: "00:00"
      })
    })

    //监听音乐进度
    this.backgroundAudio.onTimeUpdate(() => {
      let currentTime = moment(this.backgroundAudio.currentTime * 1000).format("mm:ss")

      let currentWidth = this.backgroundAudio.currentTime / this.backgroundAudio.duration * 450
      this.setData({
        currentTime,
        currentWidth
      })
    })

  },
  changePlayState(isPlay) {
    this.setData({
      isPlay
    })
    appInstance.globalData.isMusicPlay = isPlay

  },
  //获取音乐详情
  async getMusicDetail(id) {
    let {
      data: {
        songs
      }
    } = await request({
      url: "/song/detail",
      data: {
        ids: id
      }
    })

    let durationTime = moment(songs[0].dt).format("mm:ss")
    this.setData({
      song: songs[0],
      durationTime
    })

    wx.setNavigationBarTitle({
      title: songs[0].name,
    });
  },
  //控制音乐播放
  handlePlay() {
    let isPlay = !this.data.isPlay
    // this.setData({
    //   isPlay
    // })

    let {
      currentId,
      musicLink
    } = this.data

    this.musicControl(isPlay, currentId, musicLink)
  },

  //控制音乐播放暂停
  async musicControl(isPlay, currentId, musicLink) {

    if (isPlay) {

      if (!musicLink) {
        //获取音乐链接
        let {
          data: {
            data
          }
        } = await request({
          url: "/song/url",
          data: {
            id: currentId
          }
        })
        musicLink = data[0].url

        if (!musicLink) {
          wx.showToast({
            title: '暂无音乐版权',
            icon: 'none',
          });
        } else {
          this.setData({
            musicLink
          })
        }


      }

      this.backgroundAudio.src = musicLink
      this.backgroundAudio.title = this.data.song.name
    } else {
      this.backgroundAudio.pause()
    }
  },
  //切换歌曲

  handleSwitch(e) {

    this.backgroundAudio.stop()

    let type = e.currentTarget.id

    //订阅消息
    PubSub.subscribe("musicId", (msg, musicId) => {

      this.getMusicDetail(musicId)

      this.musicControl(true, musicId)

      //取消订阅
      PubSub.unsubscribe("musicId")
    })

    //发布消息
    PubSub.publish('switchType', type)
  },

  //喜欢音乐
  async loveMusic() {
    let {
      currentId,
      isLove
    } = this.data
    this.setData({
      isLove: !isLove
    })
    let res = await request({
      url: "/like",
      data: {
        id: currentId,
        like: this.data.isLove
      }
    })

    if (!isLove) {
      wx.showToast({
        title: '成功添加到我喜欢的音乐',
        icon: 'none',
      });
    } else {
      wx.showToast({
        title: '已取消喜欢',
        icon: 'none',
      });
    }
  },

  //音乐循环
  changeLoop() {
    let {
      isLoop
    } = this.data
    isLoop = !isLoop

    this.setData({
      isLoop
    })
  },
  onunload: function () {
    //取消订阅
    PubSub.unsubscribe("musicId")
  }

})